package com.whcoding.multithreading.test;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.*;

/**
 * @program: spring-boot-learning
 * @description:
 * @author: whcoding
 * @create: 2022-09-16 15:22
 **/
public class ThredQueryCallableTest2 {
	static class ThredQuery implements Callable {

		/**
		 * 查询参数
		 */
		private List<Integer> parms;

		/**
		 * 返回值
		 */
		private Object object;

		public ThredQuery(List<Integer> parms) {
			this.parms = parms;
		}

		@Override
		public Object call() throws InterruptedException {
			// 查询数据库
			System.out.println("查询条件：--->" + parms);
			// 模拟查询出的数据
			object = "ID：" + parms + "查询的数据";
			return object;
		}
	}

	public static void main(String[] args) throws ExecutionException, InterruptedException {
		long start = System.currentTimeMillis();
		queryThred();
		long finish = System.currentTimeMillis();
		long timeElapsed = finish - start;
		System.out.println("耗时" + timeElapsed+ "毫秒");
	}



	public static void queryThred() throws InterruptedException, ExecutionException {
		//返回结果
		List<Object> result = new ArrayList<>();
		//模拟需要查询的ID
		List<Integer> ids =new ArrayList<>(16);
		for (int i = 0; i <1000000 ; i++) {
			ids.add(i);
		}

		// 要开的线程数量
		int threadNum = 5;
		// 拆分查的idlist
		List<List<Integer>> smallerLists = Lists.partition(ids, ids.size()/threadNum);

		// 1.创建线程池
		ExecutorService executorService = Executors.newFixedThreadPool(threadNum);

		//2.分配任务单个执行
		for (int i = 0; i < threadNum; i++) {
			ThredQuery thredQuery = new ThredQuery(smallerLists.get(i));
			Future<ThredQuery> tq=executorService.submit(thredQuery);
			result.add(tq.get());
			System.out.println("线程名称"+i+"返回值是:"+tq.get());
		}

		//3.关闭线程池
		executorService.shutdown();

		//4.输出结果
		System.out.println("查询出的数据：" + result.size());
		for (Object o : result) {
			System.out.println(o.toString());
		}


	}
}
